<template>
	<view class="mask">
		<view class="header">
			答题卡
			<view class="close-btn" @click="close"> <uni-icons type="closeempty" size="20"></uni-icons></view>
		</view>
		<view class="status">
			<text class="title">状态说明:</text>
			<view class="circular blue" />
			<text class="sub-title">已作答</text>
			<view class="circular white" />
			<text class="sub-title">未作答</text>
		</view>
		<view class="main">
			<view class="title"> 一、单选题（本大题共{{ singleList.length }}小题，共{{ getTotalScore(singleList) }}分）</view>
			<view class="circular-box">
				<view class="circular white" v-for="(item,index) in singleList"
					:class="{ blue: isCorrect(item), red: isError(item) }" :key="item.examinationId"
					@click="link(item.navIndex)">{{ index + 1 }}</view>
			</view>
			<view class="title">
				二、多选题（本大题共{{ multipleList.length }}小题，共{{ getTotalScore(multipleList) }}分）</view>
			<view class="circular-box">
				<view class="circular white" v-for="(item,index) in multipleList"
					:class="{ blue: isCorrect(item), red: isError(item) }" :key="item.examinationId"
					@click="link(item.navIndex)">{{ (singleList.length || 0) + index + 1 }}</view>
			</view>
			<view class="title">
				三、判断题（本大题共{{ judgementList.length }}小题，共{{ getTotalScore(judgementList) }}分）</view>
			<view class="circular-box">
				<view class="circular white" v-for="(item,index) in judgementList"
					:class="{ blue: isCorrect(item), red: isError(item) }" :key="item.examinationId"
					@click="link(item.navIndex)">{{ (singleList.length || 0) + (multipleList.length || 0) + index + 1}}
				</view>
			</view>
		</view>
		<view class="footer" v-if="!isView">
			<view class="submit" @click="tipDialogVisible = true">提交试卷</view>
		</view>
		<OnlineExamTipDialog v-model="tipDialogVisible" @confirm="handleSubmit" :type="noDoneNum ? '' : 'primary'">
			<view>{{ noDoneNum ? '温馨提示' : '恭喜您' }}</view>
			<view>{{ noDoneNum ? `您还有${noDoneNum}题未做，确认交卷吗` : '题目已全部答完，确认交卷吗' }}</view>
		</OnlineExamTipDialog>
		<examination-dialog v-model="examinationDialogVisible" :status="examinationDialogStatus"
			:data="examinationResult" @ended="handleEnded" />
	</view>
</template>

<script>
	import {
		getSimulationTestDetail,
		submitOneExam,
		submitExam
	} from '@/api/educational-training/simulation-test.js'
	import {
		getExaminationList,
		getExaminationRandom
	} from '@/api/educational-training/examination.js'
	import {
		mapMutations,
		mapState,
		mapActions
	} from 'vuex'
	import {
		get,
		sum
	} from 'lodash'
	import TipDialog from "../online-examination/components/TipDialog";
	import {
		examinationStatus
	} from '@/utils/constant'
	import {
		handin,
		saveTestRecord
	} from "../../../api/educational-training/examination";
	import ExaminationDialog from "../online-examination/components/ExaminationDialog.vue";
	import OnlineExamTipDialog from "../online-examination/components/OnlineExamTipDialog";
	export default {
		name: 'online-answer-sheet',

		components: {
			TipDialog,
			ExaminationDialog,
			OnlineExamTipDialog
		},

		props: {},

		data() {
			return {
				isSubmit: false,
				examinationStatus,
				id: null,
				simulationId: null,
				paperData: {
					judgementList: [],
					multipleTitle: [],
					singleTitle: []
				},
				mode: '', // view 查看
				type: '', // ''.正常考试 1.题库训练 2.模拟考试
				typeId: '',
				tipDialogVisible: false,
				examinationDialogVisible: false,
				examinationDialogStatus: examinationStatus.PAUSE,
				examinationResult: {},
				urlParams: {}
			}
		},

		onLoad({
			id,
			simulationId,
			mode,
			type,
			data
		}) {
			this.id = id
			this.simulationId = simulationId
			this.mode = mode
			this.type = type
			this.typeId = id

			if (type == '2') {
				let dataObj = JSON.parse(data)
				this.urlParams = dataObj
				this.count = dataObj.count
			}
		},

		onShow() {
			this.fetchData()
		},

		computed: {
			...mapState({
				examDetailList: (state) => state.onlineExam.examDetailList
			}),
			isView() {
				return this.mode === 'view'
			},
			singleList() {
				return get(this.paperData, 'singleList', []).map((item, index) => ({
					...item,
					navIndex: index
				}))
			},
			multipleList() {
				return get(this.paperData, 'multipleList', []).map((item, index) => ({
					...item,
					navIndex: index + this.singleList.length
				}))
			},
			noDoneNum() {
				return this.examDetailList.filter(item => !item.selectOptionIds.length).length
			},
			judgementList() {
				return get(this.paperData, 'judgementList', []).map((item, index) => ({
					...item,
					navIndex: index + this.singleList.length + this.multipleList.length
				}))
			}
		},

		watch: {},

		created() {},

		mounted() {},

		destroyed() {},

		methods: {
			...mapActions(['submitPapel']),
			...mapMutations(['setCurrentPaperIndex']),
			async fetchData() {
				if (this.isView) {
					let res
					if (this.id) {
						res = await reqGetDetail(this.id)
					}
					if (this.simulationId) {
						res = await mockTestRecordDetail(this.simulationId)
					}
					this.paperData = res.data
				} else {
					const {
						data,
						code
					} = await getSimulationTestDetail(this.id)
					this.paperData = data
					let singleList = []
					let multipleList = []
					let judgementList = []
					for (let i of this.paperData.questionTypes) {
						i.type = i.questionType

						if (i.type === '1') {
							for (let j of i.questionList) {
								j.score = i.score
								j.totalNum = i.totalNum
								j.totalScore = i.totalScore
								j.type = i.type
								singleList.push(j)
							}

						} else if (i.type === '2') {
							for (let j of i.questionList) {
								j.score = i.score
								j.totalNum = i.totalNum
								j.totalScore = i.totalScore
								j.type = i.type
								multipleList.push(j)
							}

						} else {
							for (let j of i.questionList) {
								j.score = i.score
								j.totalNum = i.totalNum
								j.totalScore = i.totalScore
								j.type = i.type
								judgementList.push(j)
							}
						}
					}
					this.paperData.singleList = singleList
					this.paperData.multipleList = multipleList
					this.paperData.judgementList = judgementList
				}
			},
			async getExamList(type, id) {
				let params = {
					examinationTypeId: id
				}
				let res
				// type = 1 ，题库训练
				if (type == 1) {
					res = await getExaminationList(params)
				}
				// type = 2 ，模拟考试
				if (type == 2) {
					params.examinationCount = this.urlParams.count
					res = await getExaminationRandom(params)
				}
				this.paperData = res.data

			},
			getTotalScore(list) {
				return sum(list.map((item) => item.score))
			},
			close() {
				uni.navigateBack()
			},
			isCorrect({
				navIndex,
				correctFlag
			}) {
				if (this.isView) {
					return correctFlag
				} else {
					return get(this.examDetailList, `${navIndex}.selectOptionIds.length`, 0)
				}
			},
			isError({
				correctFlag
			}) {
				return this.isView && !correctFlag
			},
			link(index) {
				this.setCurrentPaperIndex(index)
				this.close()
			},
			async handleSubmit() {
				// 快速点击会导致重复提交
				if (this.isSubmit) {
					return
				}
				this.isSubmit = true
				try {
					await submitExam(this.id)
				} catch (err) {
					console.log(err)
				}
				getSimulationTestDetail(this.id).then(({
					data
				}) => {
					if (data.score < data.passScore) {
						this.examinationDialogStatus = examinationStatus.FAIL
					} else {
						this.examinationDialogStatus = examinationStatus.SUCCESS
					}
					this.examinationResult = {
						score: data.score,
						errors: data.errorCount,
						qualifying: this.paperData.passScore
					}
					this.examinationDialogVisible = true
				}).finally(() => {
					this.isSubmit = false
				})
			},

			handleEnded() {
				uni.navigateBack({
					delta: 3
				})
			},
		}
	}
</script>

<style scoped lang="scss" type="text/scss">
	.mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  padding-top: 50rpx;
}
.header {
  position: relative;
  height: 88rpx;
  line-height: 88rpx;
  width: 100%;
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  text-align: center;

  .close-btn {
    position: absolute;
    top: 0;
    left: 30rpx;
  }
}
.status {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  height: 77rpx;
  padding-left: 30rpx;
  background: #f5f5f5;

  .title {
    color: #333333;
    margin-right: 10rpx;
  }
  .sub-title {
    color: #666666;
    margin-right: 30rpx;
  }
  .circular {
    margin-right: 10rpx;
  }
}
.circular {
  width: 34rpx;
  height: 34rpx;
  border-radius: 50%;
}
.white {
  background: #ffffff;
  border: 1px solid #bbbbbb;
  color: #999999;
}
.blue {
  background: #ebf2f5;
  border: 1px solid #88b4c4;
  color: #88B4C4;
}
.red {
  color: #A14430;
  background: #EFDEDB;
  border: 1px solid #A14430;
}
.main {
	overflow: auto;
	height: calc(100vh - 400rpx);
  padding: 30rpx 10rpx 40rpx;

  .circular {
    width: 90rpx;
    height: 90rpx;
    margin-left: 30rpx;
    margin-top: 30rpx;
    text-align: center;
    line-height: 90rpx;
  }
  .circular-box {
    display: flex;
		flex-wrap: wrap;
    margin-bottom: 50rpx;
  }
}
.footer {
  position: fixed;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  .submit {
    text-align: center;
    width: 600rpx;
    height: 98rpx;
    line-height: 98rpx;
    font-size: 36rpx;
    color: #ffffff;
    background: #454a5e;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
  }
}
</style>
